package com.anmoyi.web.controller;

import com.alibaba.fastjson.JSON;
import com.anmoyi.common.*;
import com.anmoyi.common.exception.TokenException;
import com.anmoyi.model.po.User;
import com.anmoyi.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
public class TokenController extends BaseController {


    private static final Logger logger = LoggerFactory.getLogger(TokenController.class);


    @Autowired
    private UserService userService;


    /**
     * 检查token是否有效
     * @param requestString
     * @return
     */
    @PostMapping(value = "/tokenCheck")
    public String tokenCheck(@RequestBody String requestString){
        logger.info("检查token是否有效");


        logger.info(requestString);

        Packet packet = null;

        try {
            packet = JSON.parseObject(requestString, Packet.class);
        } catch (Exception e) {
            logger.error("评论参数异常\n" ,e);
            return responseToClient(AppError.APP_JSON_INVALID_ERROR);
        }


        String token = packet.getToken();


        String phone = null;
        try {
            phone = TokenUtil.getEmail(token);
        } catch (TokenException e) {
            logger.error("检查token是否有效\n" ,e);
            return responseToClient(AppError.APP_JSON_INVALID_ERROR);
        }

        logger.info("phone is : " + phone);

        User user = userService.getByPhone(phone);
        if (null == user) {
            logger.info("token无效，用户不存在");
            return responseToClient(AppError.APP_JSON_INVALID_ERROR);
        }


        if (!user.getToken().equals(token)){
            logger.info("token无效，token错误");
            return responseToClient(AppError.APP_JSON_INVALID_ERROR);
        }


        logger.info("user is : " + user);


        long dif = DateUtil.getMinute(user.getUpdateTime());
        if (dif > Const.USER_LOGIN_INVALID_TIME) {// 单位，分钟
            //需要用户重新登陆
            logger.info("token无效，过期");
            return responseToClient(AppError.APP_JSON_INVALID_ERROR);
        }


        user.setUpdateTime(new Date());
        userService.update(user);


        return responseToClient(AppError.APP_OK);

    }


}

